<template>
  <div class="page flex-center">
    <div class="sign-box">
      <h1 class="title">{{ t('login') }}</h1>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="86px">
        <el-form-item :label="t('form.username')" prop="account">
          <el-input
            v-model="form.account"
            :placeholder="t('form.usernameHolder')"
            prefix-icon="user"
          >
          </el-input>
        </el-form-item>
        <el-form-item :label="t('form.password')" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            :placeholder="t('form.passwordHolder')"
            prefix-icon="lock"
          >
          </el-input>
        </el-form-item>
        <el-form-item label>
          <el-button type="primary" class="w100p" :loading="loading" @click="doLogin">{{
            t('login')
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { login } from '@/apis/login'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const router = useRouter()
const store = useStore()
const formRef = ref()
const loading = ref(false)

// 定义登录表单
const form = reactive({
  account: 'admin',
  password: 'admin'
})

const rules = computed(() => {
  return {
    account: [
      { required: true, message: t('form.usernameHolder'), trigger: ['blur', 'change'] },
      {
        pattern: /^[a-zA-Z][a-zA-Z0-9_-]{3,31}$/,
        message: t('form.usernameError'),
        trigger: ['change', 'blur']
      }
    ],
    password: {
      required: true,
      min: 4,
      message: t('form.passwordError'),
      trigger: ['change', 'blur']
    }
  }
})

const doLogin = () => {
  formRef.value.validate((valid) => {
    console.log('valid', valid)
    if (!valid) {
      return
    }
    // 执行登录接口的逻辑
    console.log('开始执行登录')
    loading.value = true

    login(form)
      .then((res) => {
        console.log('登录成功了')
        console.log('res', res)
        // console.log('res====',res);
        store.commit('user/setToken', res.data.token)
        store.dispatch('user/refreshInfo')

        store.commit('setRouteLoaded')
        router.push('/')
      })
      .finally(() => {
        loading.value = false
      })
  })
}
</script>

<style scoped lang="scss">
.page {
  height: 100%;
  background-size: cover;
  background-image: url('@/assets/images/1.jpg');
}
.sign-box {
  width: 400px;
  background: #fff;
  padding: 30px 50px 20px 30px;
  border-radius: 4px;
  box-shadow: 0 0 10px #022c44;
}
.title {
  text-align: center;
  font-size: 20px;
  line-height: 30px;
  margin-top: 0;
  margin-bottom: 10px;
  color: #000;
}
</style>
